package cn.mogugo.joke.tld;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.lang.StringUtils;
import org.hibernate.util.StringHelper;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.mogugo.joke.manager.JokeObjManager;
import cn.mogugo.joke.model.JokeObj;
import cn.mogugo.joke.model.JokeWeb;
import cn.mogugo.util.tools.NumberTools;
import cn.mogugo.util.tools.StringTools;

public class JokeObjDetailTld extends BodyTagSupport {

	public JokeObj jo;
	
	public Integer[] nextAndLastJokeObjId;
	
	
	public int doStartTag() throws JspTagException {
		
		WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(pageContext.getServletConfig().getServletContext());
		JokeObjManager jokeObjManager = (JokeObjManager) context.getBean("jokeObjManager");		

		Object obj = pageContext.getAttribute("jo");
		if(obj != null){
			jo = (JokeObj)obj;
		}else{
			String id = pageContext.getRequest().getParameter("id");
			if(StringUtils.isNotBlank(id)){
				Integer jokeId = NumberTools.formatObject2IntDefaultZeroNoExp(id);
				if(jokeId != 0){
					jo = jokeObjManager.getById(Integer.valueOf(id));
				}
			}
		}
		
		if(jo != null){
			Integer clickNumber = jo.getClick_number();
			jo.setClick_number(clickNumber + 1);
			jokeObjManager.saveObj(jo);
		}

		
		return this.EVAL_BODY_AGAIN;
	}
	
	
	public int doEndTag() throws JspException {
		if(jo != null){
			BodyContent bc = getBodyContent();
			String body = bc.getString();
			body = StringHelper.replace(body, "$_jo_joke_title" , jo.getJoke_title());
			body = StringHelper.replace(body, "$_jo_joke_id" , jo.getId().toString());
			body = StringHelper.replace(body, "$_jo_click_number" , jo.getClick_number()+"");
			body = StringHelper.replace(body, "$_jo_joke_content" , StringTools.textareaForLine(jo.getJoke_content()));
			
			body = StringHelper.replace(body, "$_jo_category_name" , jo.getJokeCategory().getCategory_name());
			body = StringHelper.replace(body, "$_jo_category_id" , jo.getJokeCategory().getId()+"");
			
			JokeWeb jw = jo.getJokeWeb();
			if(jw != null){
				body = StringHelper.replace(body, "$_jo_web_name" , jw.getWeb_name());
			}
			
	        try {
	            pageContext.getOut().print(body);
	        } catch (IOException e) {
	        }
		}


		return this.EVAL_PAGE;
				
		
	}



	
	
	
	
}
